<?php namespace module\button;
use module\HdSite;
use system\model\Button;

class Site extends HdSite {

//    菜单列表
    public function AdminLists(){
        $data = Db::table('button')->get();
        View::with('data',$data);
        $this->display('lists');
    }

    //以site 开始的是后台动作,以web 开始的是前台动作
    public function AdminPost(){
        $id = Request::get('id');

        if(IS_POST){
            $module = new Button();
            $module->id = $id;
            $module->name = Request::post('name');
            $module->data = Request::post('data');
            $module->status = 0;
            $module->save();
            message('保存成功',site_url('site/lists'),'success');
        }
        if($id){
//           编辑
            $field = Db::table('button')->find($id);
            View::with('field',$field);
        }

        $this->display('post');
    }

    /**
     * 消息按钮推送
     */
    public function AdminPush(){
        $id = Request::get('id');
        $module = new Button();
        $button = $module->find($id);
//        如果存在内容就发给微信
        if($button){
            $res = Wx::instance('button')->create($button['data']);
//            如果推送消息成功
            if($res['errcode'] == 0){
                $oldbutton = $module->where('status',1)->first();
                if($oldbutton){
                    $oldbutton->status = 0;
                    $oldbutton->save();
                }
                $button->status = 1;
                $button->save();
                message( '推送成功', site_url( 'site/lists' ), 'message' );
            }else{
                message( '推送失败', site_url( 'site/lists' ), 'message' );
            }
        }

    }

//    删除
    public function AdminDel(){
        $id = Request::get('id');
        $module = new Button();
        $button = $module->find($id);
//        如果存在数据还是启用的就删除微信
        if($button){
            if($button['status'] == 1){
                $res = Wx::instance('button')->del();
                if($res != 0){
                    message('删除失败',site_url('site/lists'),'message');
                }
            }
            $module->delete($id);
            message('删除成功',site_url('site/lists'),'message');
        }
    }



}